const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const questions = require('./constants/questions');

const checkConfigFile = () => {
  const filePath = path.join(global.cwdPath, './.yhpagerc.js');
  return new Promise((resolve, reject) => {
    const isExsit = fs.existsSync(filePath);
    if (isExsit) {
      global.log.warn('yhpagerc.js is exsited!!');
      const d = require(filePath);

      if (!d || !d.config) {
        // 没有配置项直接重新填写
        resolve({ code: 2 });
      }
      // 有配置项
      resolve({ code: 1, keys: Object.keys(d.config) });
      // fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => {
      //     if (err) {
      //         global.log.error(err)
      //         reject(new Error('unknown'))
      //     }
      //     // 查询是否有config
      //     const d = data
      //     resolve({ code: 1 })
      // })
    } else {
      resolve({ code: 2 });
    }
  });
};

const createConfigFile = (userKeys = [], myAnswer = {}) => {
  const filePath = path.join(global.cwdPath, './.yhpagerc.js');
  const ownKeys = Object.keys(questions);
  const notExsitedKeys = ownKeys.filter((k) => !(k in userKeys));
  const promptsQuestions = notExsitedKeys.map((key) => ({
    name: key,
    ...questions[key],
  }));

  const localConfig = {};
  ownKeys.forEach((k) => {
    localConfig[k] = questions[k].default;
  });
  return inquirer.prompt(promptsQuestions, myAnswer).then((answser) => {
    const res = {
      ...localConfig,
      ...answser,
    };
    const { language, styleType } = res;
    if (language === 'typescript' && styleType === 'styled-components') {
      fs.writeFileSync(
        filePath,
        `
                exports.config = ${JSON.stringify(res)}`
      );
      return Promise.resolve(res);
    }
    global.log.fail('these types are not supported!!');
    return Promise.reject(new Error());
  });
};

const readConfigFile = () =>
  // eslint-disable-next-line implicit-arrow-linebreak
  new Promise((resolve) => {
    // eslint-disable-next-line import/no-dynamic-require,global-require
    const { config } = require(path.join(global.cwdPath, './.yhpagerc.js'));

    if (Object.keys(config).length - 1 < Object.keys(questions).length) {
      return createConfigFile(config, config).then((res) => resolve(res));
    }
    resolve(config);
  });

module.exports = {
  checkConfigFile,
  createConfigFile,
  readConfigFile,
};
